<template>
    <div>
        <nav-popup title="Head保养"></nav-popup>
        <!-- 监听键盘事件以区分扫码枪和手动输入 -->
        <van-field v-model="form.searchValue" label="headSN" maxlength="25" placeholder="请输入headSN"
            @keyup.enter="handleScannerInput" @input="manualInput = true" @focus="manualInput = false">
        </van-field>

        <van-field v-model="form.selectedYear" readonly label="选择年份" placeholder="请选择年份" is-link
            @click="showPicker = true" />

        <van-popup v-model="showPicker" round position="bottom">
            <van-picker :columns="yearOptions" show-toolbar type="year" @confirm="onYearConfirm"
                @cancel="showPicker = false" />
        </van-popup>

        <div class="search">
            <van-button type="info" block round @click="handleSearch">搜索</van-button>
        </div>

        <van-tabs v-model="active" type="card" color="#1989fa">
            <van-tab title="周保养">
                <van-calendar :show-title="false" type="single" color="#1989fa" :poppable="false" :show-confirm="false"
                    :style="{ height: '500px' }" :formatter="formatter" :min-date="minDate" :max-date="maxDate"
                    @confirm="handleWeekDateClick" />
            </van-tab>

            <van-tab title="月保养">
                <div class="month-grid">
                    <div v-for="month in months" :key="month"
                        :class="['month-item', highlightedMonths.includes(monthToNumber(month)) ? 'highlighted-month' : '']"
                        @click="handleMonthClick(month)">
                        <span>{{ month }}</span>
                        <div v-if="highlightedMonths.includes(monthToNumber(month))" style="margin-top: 5px;">已保养</div>
                        <div v-else style="margin-top: 5px;">未保养</div>
                    </div>
                </div>

            </van-tab>

            <van-tab title="季保养">
                <div class="quarter-grid">
                    <div v-for="quarter in quarters" :key="quarter"
                        :class="['quarter-item', highlightedQuarters.includes(quarterToNumber(quarter)) ? 'highlighted-quarter' : '']"
                        @click="handleQuarterClick(quarter)">
                        <span>{{ quarter }}</span>
                        <div v-if="highlightedQuarters.includes(quarterToNumber(quarter))" style="margin-top: 5px;">
                            已保养</div>
                        <div v-else style="margin-top: 5px;">未保养</div>
                    </div>
                </div>
            </van-tab>
            <van-tab title="年保养">
                <div class="year-grid">
                    <div v-for="year in yearOptions" :key="year"
                        :class="['year-item', highlightedYears.includes(parseInt(year)) ? 'highlighted-year' : '']"
                        @click="handleYearClick(year)">
                        <span>{{ year }}</span>
                        <div v-if="highlightedYears.includes(parseInt(year))" style="margin-top: 5px;">已保养</div>
                        <div v-else style="margin-top: 5px;">未保养</div>
                    </div>
                </div>
            </van-tab>

        </van-tabs>
        <!-- 周保养弹出层 -->
        <van-popup v-model="showWeekInfoVisible" position="bottom" :style="{ height: '40%' }">
            <div v-if="selectedWeekDateInfo" class="week-info-popup">
                <h3 class="popup-title">保养详情</h3>
                <van-cell-group>
                    <van-cell title="周保养日期" :value="selectedWeekDateInfo.mainteDate" />
                    <van-cell title="保养员工姓名" :value="selectedWeekDateInfo.mainteEmpName" />
                    <van-cell title="保养员工" :value="selectedWeekDateInfo.mainteEmpNo" />
                    <van-cell title="备注信息" :value="selectedWeekDateInfo.mainteMark" />
                </van-cell-group>
                <div class="popup-actions">
                    <van-button type="primary" block round @click="showWeekInfoVisible = false">关闭</van-button>
                </div>
            </div>
        </van-popup>
        <!-- 月保养弹出层 -->
        <van-popup v-model="showMonthInfoVisible" position="bottom" :style="{ height: '40%' }">
            <div v-if="selectedMonthDateInfo" class="week-info-popup">
                <h3 class="popup-title">保养详情</h3>
                <van-cell-group>
                    <van-cell title="月保养日期" :value="selectedMonthDateInfo.mainteDate" />
                    <van-cell title="保养员工姓名" :value="selectedMonthDateInfo.mainteEmpName" />
                    <van-cell title="保养员工" :value="selectedMonthDateInfo.mainteEmpNo" />
                    <van-cell title="备注信息" :value="selectedMonthDateInfo.mainteMark" />
                </van-cell-group>
                <div class="popup-actions">
                    <van-button type="primary" block round @click="showMonthInfoVisible = false">关闭</van-button>
                </div>
            </div>
        </van-popup>
        <!-- 季保养弹出层 -->
        <van-popup v-model="showQuarterInfoVisible" position="bottom" :style="{ height: '40%' }">
            <div v-if="selectedQuarterDateInfo" class="week-info-popup">
                <h3 class="popup-title">保养详情</h3>
                <van-cell-group>
                    <van-cell title="月保养日期" :value="selectedQuarterDateInfo.mainteDate" />
                    <van-cell title="保养员工姓名" :value="selectedQuarterDateInfo.mainteEmpName" />
                    <van-cell title="保养员工" :value="selectedQuarterDateInfo.mainteEmpNo" />
                    <van-cell title="备注信息" :value="selectedQuarterDateInfo.mainteMark" />
                </van-cell-group>
                <div class="popup-actions">
                    <van-button type="primary" block round @click="showQuarterInfoVisible = false">关闭</van-button>
                </div>
            </div>
        </van-popup>
        <!-- 年保养弹出层 -->
        <van-popup v-model="showYearInfoVisible" position="bottom" :style="{ height: '40%' }">
            <div v-if="selectedYearDateInfo" class="week-info-popup">
                <h3 class="popup-title">保养详情</h3>
                <van-cell-group>
                    <van-cell title="月保养日期" :value="selectedYearDateInfo.mainteDate" />
                    <van-cell title="保养员工姓名" :value="selectedYearDateInfo.mainteEmpName" />
                    <van-cell title="保养员工" :value="selectedYearDateInfo.mainteEmpNo" />
                    <van-cell title="备注信息" :value="selectedYearDateInfo.mainteMark" />
                </van-cell-group>
                <div class="popup-actions">
                    <van-button type="primary" block round @click="showYearInfoVisible = false">关闭</van-button>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script>
import dayjs from 'dayjs';
import NavPopup from './NavPopup.vue';
import { getHeadSNSearch, getHeadSNMainteData } from '@/network/headSN';
import { Toast } from 'vant';
export default {
    components: {
        NavPopup,
    },
    data() {
        return {
            form: {
                searchValue: '',
                selectedYear: dayjs().year(),
            },
            minDate: new Date(), // 默认日期可选最小值
            maxDate: new Date(), // 默认日期可选最大值
            active: 0,
            showPicker: false,
            showWeekInfoVisible: false,
            showMonthInfoVisible: false,
            showQuarterInfoVisible: false,
            showYearInfoVisible: false,
            selectedWeekDateInfo: null, // 存储被点击的保养日期信息
            selectedMonthDateInfo: null,
            selectedQuarterDateInfo: null,
            selectedYearDateInfo: null,
            highlightedMonths: [],
            highlightedQuarters: [],
            highlightedYears: [],
            yearOptions: this.getYearOptions(),
            weekMainteData: [], // 存放所有的周保养数据
            monthMainteData: [],
            quarterMainteData: [],
            yearMainteData: [],
            months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
            quarters: ['一季度', '二季度', '三季度', '四季度'],

            scanData: "",
            lastTime: 0,
            lastCode: null,
            isAndroid: false,
            isIOS: false,
            searchVisible: false
        };
    },
    mounted() {
        const nowDate = new Date();
        const dateY = nowDate.getFullYear();

        // 初始化所选年份为当前年份
        this.form.selectedYear = dateY.toString();
        this.yearOptions = this.getYearOptions(); // 设置年份选项

        // 设置日期可选最小值和最大值为当前年份
        this.updateDateRange(dateY);
        this.getData();

        this.detectPlatform(); // 检测平台


        const eventType = this.isIOS ? "keyup" : "keypress"; // 使用不同的事件
        document.addEventListener(eventType, this.handleKeyPress);

    },
    beforeDestroy() {
        const eventType = this.isIOS ? "keyup" : "keypress";
        document.removeEventListener(eventType, this.handleKeyPress);
    },
    methods: {
        detectPlatform() {
            const userAgent = navigator.userAgent || navigator.vendor || window.opera;
            this.isAndroid = /android/i.test(userAgent);
            this.isIOS = /iPad|iPhone|iPod/.test(userAgent) && !window.MSStream;
        },
        handleKeyPress(e) {
            const nextCode = e.keyCode || e.which;
            const nextTime = new Date().getTime();
            if (nextCode === 13) {
                if (this.scanData.length >= 3) {
                    this.processScanData(this.scanData);
                }
                this.resetScanData();
                return;
            }
            if (this.lastTime && nextTime - this.lastTime > 30) {
                this.scanData = e.key;
            } else {
                this.scanData += e.key;
            }

            this.lastTime = nextTime;
            this.lastCode = nextCode;
        },
        resetScanData() {
            this.scanData = "";
            this.lastTime = 0;
            this.lastCode = null;
        },
        processScanData(data) {
            this.form.searchValue = data
            console.log("扫码数据:", data);
        },

        getYearOptions() {
            const currentYear = dayjs().year();
            const years = [];
            for (let i = currentYear - 5; i <= currentYear; i++) {
                years.push(i.toString());
            }
            return years;
        },
        onYearConfirm(value) {
            this.form.selectedYear = value;
            this.showPicker = false;
        },
        async handleSearch() {
            this.searchVisible = true
            this.updateDateRange(this.form.selectedYear);
            await this.getData();  // 在点击搜索后才调用获取数据
        },
        async getData() {
            try {
                const res = await getHeadSNMainteData({ headSN: this.form.searchValue, year: this.form.selectedYear });
                console.log(res);
                if (res) {
                    this.weekMainteData = res.data.weekMainteInfo.data;
                    this.monthMainteData = res.data.monthMainteInfo.data
                    this.quarterMainteData = res.data.quarterMainteInfo.data
                    this.yearMainteData = res.data.yearMainteInfo.data

                    this.highlightedMonths = this.monthMainteData.map(item => dayjs(item.mainteDate).month() + 1); // 提取月份
                    this.highlightedQuarters = this.quarterMainteData.map(item => Math.floor(dayjs(item.mainteDate).month() / 3) + 1); // 1到4的数字
                    this.highlightedYears = this.yearMainteData.map(item => dayjs(item.mainteDate).year());

                    if (this.searchVisible) {
                        Toast.success('搜索成功');
                        this.searchVisible = false
                    }
                }


            } catch (error) {
                Toast.success('搜索失败');
            }
        },
        // 自定义 formatter 用于高亮保养日期
        formatter(day) {
            const mainteDates = this.weekMainteData.map(item => dayjs(item.mainteDate).format('YYYY-MM-DD'));
            const todayStr = dayjs().format('YYYY-MM-DD'); // 获取今天的日期
            const dayStr = dayjs(day.date).format('YYYY-MM-DD');

            // 如果是保养日
            if (mainteDates.includes(dayStr)) {
                return {
                    ...day,
                    className: 'van-calendar__day selected',
                    bottomInfo: '保养日', // 优先显示保养日
                };
            }

            // 如果是今天并且不是保养日
            if (dayStr === todayStr) {
                return {
                    ...day,
                    // className: 'van-calendar__day today',
                    bottomInfo: '今天',
                };
            }

            return day; // 默认样式
        },


        handleWeekDateClick(day) {
            const dayStr = dayjs(day).format('YYYY-MM-DD');
            const selectedInfo = this.weekMainteData.find(item => dayjs(item.mainteDate).format('YYYY-MM-DD') === dayStr);
            if (selectedInfo) {
                this.selectedWeekDateInfo = selectedInfo; // 存储该日期的保养信息
                console.log('selectedWeekDateInfo', this.selectedWeekDateInfo);
                this.showWeekInfoVisible = true;
            }
        },

        updateDateRange(year) {
            this.minDate = new Date(year, 0, 1);
            this.maxDate = new Date(year, 11, 31);
        },

        // 将月份名称转换为对应的数字
        monthToNumber(monthName) {
            const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
            return monthNames.indexOf(monthName) + 1; // 转换为 1 - 12 的数字
        },
        handleMonthClick(month) {
            const monthNumber = this.monthToNumber(month); // 将中文月份转换为数字
            // 检查点击的月份是否在 highlightMonths 中
            if (this.highlightedMonths.includes(monthNumber)) {
                const selectedInfo = this.monthMainteData.find(item => dayjs(item.mainteDate).month() + 1 === monthNumber);
                if (selectedInfo) {
                    this.selectedMonthDateInfo = selectedInfo;
                    this.showMonthInfoVisible = true;
                }
            } else {
                console.log('该月份没有保养数据');
            }
        },
        quarterToNumber(quarterName) {
            const quarters = ['一季度', '二季度', '三季度', '四季度'];
            return quarters.indexOf(quarterName) + 1;
        },
        handleQuarterClick(quarter) {
            const quarterNumber = this.quarterToNumber(quarter); // 将中文季度转换为数字
            if (this.highlightedQuarters.includes(quarterNumber)) {
                const selectedInfo = this.quarterMainteData.find(
                    item => Math.floor(dayjs(item.mainteDate).month() / 3) + 1 === quarterNumber
                );
                if (selectedInfo) {
                    this.selectedQuarterDateInfo = selectedInfo;
                    this.showQuarterInfoVisible = true;
                }
            } else {
                console.log('该季度没有保养数据');
            }
        },
        handleYearClick(year) {
            const yearNumber = parseInt(year);
            if (this.highlightedYears.includes(yearNumber)) {
                const selectedInfo = this.yearMainteData.find(
                    item => dayjs(item.mainteDate).year() === yearNumber
                );
                if (selectedInfo) {
                    this.selectedYearDateInfo = selectedInfo;
                    this.showYearInfoVisible = true;
                }
            } else {
                console.log('该年份没有保养数据');
            }
        },

    },
};
</script>

<style scoped>
.search {
    margin: 10px;
}

.add {
    margin: 0 0 10px 10px;
}

.month-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin: 20px;
}

.month-item {
    background-color: #f5f5f5;
    padding: 20px;
    text-align: center;
    border-radius: 8px;
    cursor: pointer;
}

.week-info-popup {
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0px -2px 8px rgba(0, 0, 0, 0.1);
    max-height: 80vh;
    overflow-y: auto;
}

.popup-title {
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
}

.van-cell {
    font-size: 14px;
    margin-bottom: 8px;
}


::v-deep .van-calendar__day.selected {
    background-color: #1989fa;
    color: #fff;
    height: 54px;
    margin-top: 5px;
    border-radius: 4px;
}

::v-deep .van-calendar__day.today {
    background-color: #FFD700;
    color: #fff;
    height: 54px;
    margin-top: 5px;
    border-radius: 4px;
}

.van-cell__value {
    white-space: normal;
    word-wrap: break-word;
    word-break: break-all;
}

.popup-actions {
    margin-top: 16px;
    display: flex;
    justify-content: center;
}

.van-button {
    font-size: 16px;
}

.month-item.highlighted-month {
    background-color: #1989fa;
    color: #fff;
}

.quarter-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin: 20px;
}

.quarter-item {
    background-color: #f5f5f5;
    padding: 20px;
    text-align: center;
    border-radius: 8px;
    cursor: pointer;
}

.quarter-item.highlighted-quarter {
    background-color: #1989fa;
    color: #fff;
}

.year-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin: 20px;
}

.year-item {
    background-color: #f5f5f5;
    padding: 20px;
    text-align: center;
    border-radius: 8px;
    cursor: pointer;
}

.year-item.highlighted-year {
    background-color: #1989fa;
    color: #fff;
}
</style>